package com.example.qrcodecamera;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class MaterialInfoDecodeActivity extends AppCompatActivity {
    private TextView tvResult;
    private EditText etMaterialId, etMaterialnum, etweight, etvurweight;

    private MaterialDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_info_decode);

        dbHelper = new MaterialDatabaseHelper(this);
        Button btnScan = findViewById(R.id.btn_scan);
        Button btnBack = findViewById(R.id.btn_back);
        tvResult = findViewById(R.id.tv_result);
        etMaterialId = findViewById(R.id.et_material_id);
        etMaterialnum = findViewById(R.id.et_material_num);
        etweight = findViewById(R.id.et_weight);
        etvurweight = findViewById(R.id.et_curweight);

        btnScan.setOnClickListener(v -> {
            new IntentIntegrator(this)
                    .setPrompt("扫描物料信息二维码")
                    .setOrientationLocked(true)
                    .initiateScan();
        });

        btnBack.setOnClickListener(v -> finish());

        findViewById(R.id.btn_save).setOnClickListener(v -> {
            String id = etMaterialId.getText().toString().trim();
            String name = etMaterialnum.getText().toString().trim();
            String spec = etweight.getText().toString().trim();
            String weightStr = etvurweight.getText().toString().trim();

            if (id.isEmpty() || name.isEmpty() || spec.isEmpty() || weightStr.isEmpty()) {
                Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                double weight = Double.parseDouble(weightStr);
                boolean success = dbHelper.insertData(id, name, spec, weight);
                if (success) {
                    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                    clearFields();
                } else {
                    Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "重量格式错误", Toast.LENGTH_SHORT).show();
            }
        });

        // 查看数据库按钮
        findViewById(R.id.btn_view_data).setOnClickListener(v -> {
            startActivity(new Intent(this, MaterialViewActivity.class));
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null && result.getContents() != null) {
            String rawData = result.getContents();
            // 显示原始结果
            tvResult.setText("原始数据: " + rawData);

            // 清理数据并拆分
            String cleanData = rawData.replaceAll("[{} ]", "");
            String[] parts = cleanData.split(",");

            if (parts.length == 4) {
                etMaterialId.setText(parts[0].trim());
                etMaterialnum.setText(parts[1].trim());
                etweight.setText(parts[2].trim());
                etvurweight.setText(parts[3].trim());
            } else {
                Toast.makeText(this, "二维码格式错误，需包含4个字段", Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void clearFields() {
        etMaterialId.setText("");
        etMaterialnum.setText("");
        etweight.setText("");
        etvurweight.setText("");
    }
}